/*
 * Copyright (c) 2025 EasyAdmin
 * All rights reserved.
 *
 * This file is part of the [EasAdmin] project.
 * Unauthorized copying of this file, via any medium, is strictly prohibited.
 * Proprietary and confidential.
 *
 * Author: EasyAdmin ( 1073602@qq.com )
 * Website: https://www.xhxiao.com
 */
package com.easy.module.system.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.easy.framework.common.utils.Func;
import com.easy.module.system.entity.SysUserRole;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色 Mapper接口
 *
 * @author EasyAdmin ( 1073602@qq.com )
 * @date 2025-08-19
 */
public interface SysUserRoleMapper extends BaseMapper<SysUserRole>
{

    /**
     * 通过用户ID删除用户和角色关联
     *
     * @param userId 用户ID
     * @return 结果
     */
    default int deleteByUserId(Long userId){
        return delete(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userId));
    }

    /**
     * 批量删除用户和角色关联
     *
     * @param userIds 需要删除的数据ID
     * @return 结果
     */
    default int deleteBatchByUserIds(Long[] userIds) {
        return delete(Wrappers.<SysUserRole>lambdaQuery().in(SysUserRole::getUserId, userIds));
    }

    /**
     * 批量新增用户角色信息
     *
     * @param userRoleList 用户角色列表
     * @return 结果
     */
    default int addBatch(List<SysUserRole> userRoleList){
        userRoleList.forEach(userRole -> insert(userRole));
        return userRoleList.size();
    }

    /**
     * 删除用户和角色关联信息
     *
     * @param userRole 用户和角色关联信息
     * @return 结果
     */
    default int delete(SysUserRole userRole){
        return delete(Wrappers.<SysUserRole>lambdaQuery()
                .eq(SysUserRole::getUserId, userRole.getUserId())
                .eq(SysUserRole::getRoleId, userRole.getRoleId()));
    }

    /**
     * 批量取消授权用户角色
     *
     * @param roleId  角色ID
     * @param userIds 需要删除的用户数据ID
     * @return 结果
     */
    default int delete(Long roleId, Long[] userIds){

        return delete(Wrappers.<SysUserRole>lambdaQuery()
                .eq(SysUserRole::getRoleId, roleId)
                .in(SysUserRole::getUserId, userIds));
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    default Long countByRoleId(Long roleId){
        return selectCount(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getRoleId, roleId));
    }

    /**
     * 通过用户ID获取用户和角色关联
     *
     * @param userId 用户ID
     * @return 结果
     */
    default List<Long> getRoleIdListByUserId(Long userId){
        List<SysUserRole> userRoleList= selectList(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userId));
        if(Func.isNotEmpty(userRoleList)){
            return userRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        }
        return null;
    }
}
